package com.hermit.server.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.page.PageAutoDialect;
import com.hermit.server.domain.Resource;
import com.hermit.server.domain.ResourceExample;
import com.hermit.server.dto.ResourceDto;
import com.hermit.server.dto.PageDto;
import com.hermit.server.mapper.ResourceMapper;
import com.hermit.server.util.CopyUtil;
import com.hermit.server.util.UUidUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service
public class ResourceService {

    private static final Logger LOG = LoggerFactory.getLogger(ResourceService.class);

    @javax.annotation.Resource
    private ResourceMapper resourceMapper;

    /** 查询*/
    public void list(PageDto pageDto){
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());
        ResourceExample resourceExample = new ResourceExample();
        /** 根据sort来排序*/

        List<Resource> resourceList = resourceMapper.selectByExample(resourceExample);
        //查询数据
        PageInfo<Resource> pageInfo = new PageInfo<>(resourceList);
        //设置已查询条数
        pageDto.setTotal(pageInfo.getTotal());

        List<ResourceDto> resourceDtoList = new ArrayList<ResourceDto>();
        for (int i = 0; i < resourceList.size(); i++) {
            Resource resource = resourceList.get(i);
            ResourceDto resourceDto = new ResourceDto();
            BeanUtils.copyProperties(resource,resourceDto);
            resourceDtoList.add(resourceDto);
        }
        //设置最终查询结果
        pageDto.setList(resourceDtoList);
        //return pageDto;  pageDto是从前端传递来的，按道理应该有返回值，此处传入对象==返回对象，属于原地返回（杨凡专用名词）
    }
    /** 保存*/
    public void save(ResourceDto resourceDto){
        Resource resource = CopyUtil.copy(resourceDto,Resource.class);
        if(StringUtils.isEmpty(resourceDto.getId())){
            this.insert(resource);
        }else{
            this.update(resource);
        }

    }
    /**新增 */
    private void insert(Resource resource){
        resourceMapper.insert(resource);
    }
    /**修改更新 */
    private void update(Resource resource){
        resourceMapper.updateByPrimaryKey(resource);
    }
    /**删除 */
    public void delete(String id){
        resourceMapper.deleteByPrimaryKey(id);
    }

    /**保存资源树*/

    public void saveJson(String json){
        List<ResourceDto> jsonList = JSON.parseArray(json,ResourceDto.class);
        List<ResourceDto> list = new ArrayList<>();

        if(!CollectionUtils.isEmpty(jsonList)){
            for(ResourceDto d:jsonList){
                d.setParent("");
                add(list,d);
            }
        }
        LOG.info("共{}条",list.size());

        //清空数据库
        resourceMapper.deleteByExample(null);
        for(int i = 0;i < list.size();i++){
            this.insert(CopyUtil.copy(list.get(i),Resource.class));
        }
    }

    /**递归 将树型结构的节点全部取出来 放入list*/
    public void add(List<ResourceDto> list,ResourceDto dto){
        list.add(dto);
        if(!CollectionUtils.isEmpty(dto.getChildren())){
            for(ResourceDto d : dto.getChildren()){
                d.setParent(dto.getId());
                add(list,d);
            }
        }
    }

    /**
     * 列表转换为树
     * ID正排序
     */

    public List<ResourceDto> loadTree(){
        ResourceExample example = new ResourceExample();
        example.setOrderByClause("id asc");
        List<Resource> resourceList = resourceMapper.selectByExample(example);
        List<ResourceDto> resourceDtoList = CopyUtil.copyList(resourceList,ResourceDto.class);
        for(int i = resourceDtoList.size() - 1;i>=0;i--){
            //当前要移动的记录
            ResourceDto child = resourceDtoList.get(i);
            //如果当前节点没有父节点
            if(StringUtils.isEmpty(child.getParent())){
                continue;
            }
            //查找父节点
            for(int j = i - 1;j >= 0;j--){
                ResourceDto parent = resourceDtoList.get(j);
                if(child.getParent().equals(parent.getId())){
                    if(CollectionUtils.isEmpty(parent.getChildren())){
                        parent.setChildren(new ArrayList<>());
                    }
                    //添加到最前面  倒叙循环 所以在最前面添加
                    parent.getChildren().add(0,child);
                    //子节点找到父节点后删除子节点
                    resourceDtoList.remove(child);
                }
            }
        }
        return resourceDtoList;
    }
}